package com.homedo.odin.solution.controller.pc;


import com.homedo.core.common.base.controller.BaseController;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.base.dto.ResultData;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.NumberHelper;
import com.homedo.core.common.util.ParamCheckUtil;
import com.homedo.odin.solution.contract.pc.GetBrandFirmDetailReq;
import com.homedo.odin.solution.contract.pc.UserUpdateValidRequestBean;
import com.homedo.odin.solution.contract.personal.brandfirm.BrandFirmReq;
import com.homedo.odin.solution.contract.personal.brandowner.DataListResp;
import com.homedo.odin.solution.contract.personal.userhomepage.AddPopularityReq;
import com.homedo.odin.solution.contract.personal.userhomepage.AddUserIntroductionReq;
import com.homedo.odin.solution.contract.personal.userhomepage.AddVisitorReq;
import com.homedo.odin.solution.contract.personal.userhomepage.CountResp;
import com.homedo.odin.solution.contract.personal.userhomepage.IntroductionResp;
import com.homedo.odin.solution.contract.personal.userhomepage.UpdateUserBannerReq;
import com.homedo.odin.solution.contract.personal.userhomepage.UserInfoResp;
import com.homedo.odin.solution.contract.personal.userhomepage.UserSolListResp;
import com.homedo.odin.solution.contract.personal.userhomepage.VisitorListResp;
import com.homedo.odin.solution.model.request.pc.brand.BrandFirmEditRequestBean;
import com.homedo.odin.solution.model.request.pc.brand.PCBrandFirmListRequestBean;
import com.homedo.odin.solution.model.response.pc.brand.BrandFirmDetailResponseBean;
import com.homedo.odin.solution.model.response.pc.brand.BrandFirmPcListResponseBean;
import com.homedo.odin.solution.service.BrandFirmServiceImpl;
import com.homedo.odin.solution.service.UserProfileServiceImpl;
import com.homedo.odin.solution.service.bizservice.mng.MngBrandFirmsService;
import com.homedo.odin.solution.service.bizservice.pc.UserInfoService;
import com.homedo.odin.solution.service.bizservice.personal.BrandFirmBizService;
import com.homedo.odin.solution.service.bizservice.personal.CommonBizService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Api(description = "用户信息", tags = {"UserInfo"}, produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/user_info")
public class UserInfoController extends BaseController<UserInfoService> {

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    CommonBizService commonBizService;

    @Autowired
    BrandFirmBizService brandFirmBizService;

    @Autowired
    MngBrandFirmsService mngBrandFirmsService;

    @Autowired
    BrandFirmServiceImpl brandFirmService;

    @Autowired
    UserProfileServiceImpl userProfileService;

    @PutMapping
    @ApiOperation(value = "PC_更新用户基本信息", httpMethod = "PUT")
    public ResultData updateUserInfo(@Valid @RequestBody UserUpdateValidRequestBean requestBean,
            BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String defaultMessage = bindingResult.getFieldError().getDefaultMessage();
            return ResultData.newInstance(Meta.CODE_451, defaultMessage);
        }

        baseService.updateUserInfo(requestBean);
        return ResultData.newInstance(Meta.CODE_200, null);
    }

    @ApiOperation(value = "PC_获取用户信息（头像、昵称、地址、角色、主页图）", response = UserInfoResp.class, httpMethod = "GET")
    @GetMapping("/{userId}")
    public ResultData userInfo(@ApiParam("用户id") @PathVariable("userId") Integer userId) {
        ParamCheckUtil.checkUserId(userId);
        UserInfoResp resp = userInfoService.findUserInfoByUserId(userId);
        logger.info("获取用户信息返回结果：{}", resp.toJson());
        return ResultData.newInstance(resp);
    }


    @ApiOperation(value = "PC_修改主页图", notes = "PC_修改主页图", httpMethod = "PUT")
    @PutMapping("/{userId}/banner/")
    public ResultData updateBanner(@ApiParam("用户id") @PathVariable("userId") Integer userId,
            @RequestBody UpdateUserBannerReq request) {
        logger.info("修改个人主页图请求:{}", request.toJson());
        ParamCheckUtil.checkUserId(userId);
        if (StringUtils.isBlank(request.getBanner())) {
            throw new BizException(Meta.CODE_451.getCode(), "banner不能为空");
        }
        userInfoService.updateBannerByUserId(userId, request);
        return new ResultData(Meta.CODE_200);
    }

    @ApiOperation(value = "PC_获取资料列表", notes = "PC_获取资料列表", response = DataListResp.class, httpMethod = "GET")
    @GetMapping("/{userId}/resource")
    public ResultData dataList(@ApiParam("目标用户id") @PathVariable("userId") Integer userId,
            @ApiParam(value = "当前页码", required = true) @RequestParam Integer pageNum,
            @ApiParam(value = "每页数量", required = true) @RequestParam Integer pageSize) {
        ParamCheckUtil.checkUserId(userId);
        ParamCheckUtil.checkPageParam(pageNum, pageSize);
        DataListResp resp = userInfoService.findDataList(userId, pageNum, pageSize);
        return ResultData.newInstance(resp);
    }

    @ApiOperation(value = "PC_新增个人简介", notes = "PC_新增个人简介", httpMethod = "POST")
    @PostMapping("/{userId}/introduction")
    public ResultData introduction(@ApiParam("用户id") @PathVariable("userId") Integer userId,
            @RequestBody AddUserIntroductionReq request) {
        ParamCheckUtil.checkUserId(userId);
        return updateIntroduction(userId, request);
    }

    @ApiOperation(value = "PC_修改个人简介", notes = "PC_修改个人简介", httpMethod = "PUT")
    @PutMapping("/{userId}/introduction")
    public ResultData updateIntroduction(@ApiParam("用户id") @PathVariable("userId") Integer userId,
            @RequestBody AddUserIntroductionReq request) {
        ParamCheckUtil.checkUserId(userId);
        if (StringUtils.isBlank(request.getIntroduction())) {
            throw new BizException(Meta.CODE_451.getCode(), "introduction不能为空");
        }
        userInfoService.updateIntroductionByUserId(userId, request.getIntroduction());
        return new ResultData(Meta.CODE_200);
    }

    @ApiOperation(value = "PC_查看个人简介", notes = "PC_查看个人简介", response = IntroductionResp.class, httpMethod = "GET")
    @GetMapping("/{userId}/introduction")
    public ResultData selectIntroduction(@ApiParam("用户id") @PathVariable("userId") Integer userId) {
        ParamCheckUtil.checkUserId(userId);
        IntroductionResp resp = userInfoService.findIntroductionByUserId(userId);
        return ResultData.newInstance(resp);
    }

    @ApiOperation(value = "PC_新增人气值", notes = "PC_新增人气值", httpMethod = "POST")
    @PostMapping("/{userId}/popularity")
    public ResultData popularity(@ApiParam("用户id") @PathVariable("userId") Integer userId,
            @RequestBody AddPopularityReq req) {
        ParamCheckUtil.checkUserId(userId);
        commonBizService.addPopularity(req);
        return ResultData.newInstance();
    }

    @ApiOperation(value = "PC_方案列表查询", notes = "PC_方案列表查询", response = UserSolListResp.class, httpMethod = "GET")
    @GetMapping("/{userId}/solutions")
    public ResultData solList(@ApiParam("目标用户id") @PathVariable("userId") Integer userId,
            @ApiParam(value = "当前页码", required = true) @RequestParam Integer pageNum,
            @ApiParam(value = "每页数量", required = true) @RequestParam Integer pageSize) {
        ParamCheckUtil.checkUserId(userId);
        ParamCheckUtil.checkPageParam(pageNum, pageSize);
        UserSolListResp resp = userInfoService.selectSols(userId, pageNum, pageSize);
        return ResultData.newInstance(resp);
    }

    @ApiOperation(value = "PC_获取人气值和访问量", notes = "PC_获取人气值和访问量", response = CountResp.class, httpMethod = "GET")
    @GetMapping("/{userId}/statistics")
    public ResultData visitCount(@ApiParam("目标用户id") @PathVariable("userId") Integer userId) {
        ParamCheckUtil.checkUserId(userId);
        CountResp resp = userInfoService.findVisitCountByUserId(userId);
        return ResultData.newInstance(resp);
    }

    @ApiOperation(value = "PC_新增访客记录", notes = "PC_新增访客记录", httpMethod = "POST")
    @PostMapping("/{userId}/visitor")
    public ResultData visitor(@ApiParam("目标用户id") @PathVariable("userId") Integer userId,
            @RequestBody AddVisitorReq req, HttpServletRequest request) {
        ParamCheckUtil.checkUserId(userId);
        userInfoService.addVisitor(request, req);
        return ResultData.newInstance();
    }

    @ApiOperation(value = "PC_获取访客列表", notes = "PC_获取访客列表", response = VisitorListResp.class, httpMethod = "GET")
    @GetMapping("/{userId}/visitors")
    public ResultData visitorList(@ApiParam("目标用户id") @PathVariable("userId") Integer userId,
            @ApiParam(value = "当前页码", required = true) @RequestParam Integer pageNum,
            @ApiParam(value = "每页数量", required = true) @RequestParam Integer pageSize) {
        ParamCheckUtil.checkUserId(userId);
        ParamCheckUtil.checkPageParam(pageNum, pageSize);
        VisitorListResp resp = userInfoService.findVisitorList(userId, pageNum, pageSize);
        return ResultData.newInstance(resp);
    }

    @ApiOperation(value = "PC_获取所有品牌主信息", response = BrandFirmPcListResponseBean.class, httpMethod = "GET")
    @GetMapping("/brand_firms")
    public ResultData getBrandFirms(@ModelAttribute PCBrandFirmListRequestBean requestBean) {
        return ResultData.newInstance(brandFirmService.getPcBrandFirmList(requestBean));
    }

    @ApiOperation(value = "PC_申请成为品牌商", notes = "申请成为品牌商")
    @PostMapping("/brand_firms")
    public ResultData brandFirm(@RequestBody BrandFirmReq request) {
        logger.info("申请成为品牌商请求参数：{}", request.toJson());

        brandFirmBizService.applyBrandFirm(request);
        return ResultData.newInstance();
    }

    @ApiOperation(value = "PC_获取用户所属品牌商详情", notes = "PC_获取品牌商详情", response = BrandFirmDetailResponseBean.class, httpMethod = "GET")
    @GetMapping("/brand_firms/{userId}")
    public ResultData getBrandFirmDetail(@ModelAttribute("req") GetBrandFirmDetailReq req,
            @ApiParam(value = "品牌主 ID", required = true) @PathVariable("userId") int userId) {
        if (!NumberHelper.validatePositive(userId)) {
            return ResultData.newInstance(new Meta(Meta.CODE_451.getCode(), "用户ID不合法!"));
        }
        return ResultData.newInstance(brandFirmBizService.getBrandFirmDetail(req, userId));
    }

//    @ApiOperation(value = "PC_获取品牌商信息",notes = "获取品牌商信息",response = BrandFirmResp.class)
//    @GetMapping("/brand_firms/{userId}/info")
//    public ResultData getBrandFirm(@ApiParam("用户ID") @PathVariable("userId") Integer userId){
//        return ResultData.newInstance(brandFirmBizService.findBrandFirmByUserId(userId));
//    }

//    @ApiOperation(value = "PC_用户所属品牌厂商详情（根据用户查找品牌主）", response = BrandFirmDetailResponseBean.class, httpMethod = "GET")
//    @GetMapping("/brand_firms/{userId}")
//    public ResultData getBrandFirmByUser(@ApiParam(value = "用户ID", required = true) @PathVariable("userId") Integer userId,
//                                         @ApiParam(value = "当前登陆用户ID") Integer loginUserId) {
//        if(!NumberHelper.validatePositive(userId)){
//            return ResultData.newInstance(new Meta(Meta.CODE_451.getCode(), "用户ID不合法!"));
//        }
//
//        return ResultData.newInstance(mngBrandFirmsService.getBrandFirmByUserId(userId, loginUserId));
//    }

    @ApiOperation(value = "PC_编辑品牌厂商信息", response = BrandFirmDetailResponseBean.class, httpMethod = "PUT")
    @PutMapping("/brand_firms/{userId}")
    public ResultData editBrandFirm(@Valid @RequestBody BrandFirmEditRequestBean requestBean,
            BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultData.newInstance(new Meta(Meta.CODE_451.getCode(),
                    bindingResult.getFieldError().getDefaultMessage()));
        }

        mngBrandFirmsService.editBrandFirm(requestBean);

        return ResultData.newInstance();
    }

}
